package com.ruoyi.project.system.service.impl;

import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

import com.ruoyi.common.exception.CustomException;
import com.ruoyi.common.utils.ServletUtils;
import com.ruoyi.common.utils.spring.SpringUtils;
import com.ruoyi.framework.security.LoginUser;
import com.ruoyi.framework.security.service.TokenService;
import com.ruoyi.project.system.domain.*;
import com.ruoyi.project.system.mapper.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ruoyi.project.system.service.ICollegePaperService;
import org.springframework.transaction.annotation.Transactional;

/**
 * 学院试卷Service业务层处理
 *
 * @author ruoyi
 * @date 2020-11-19
 */
@Service
public class CollegePaperServiceImpl implements ICollegePaperService
{
    @Autowired
    private CollegePaperMapper collegePaperMapper;

    @Autowired
    private CollegePaperQuestionMapper collegePaperQuestionMapper;

    @Autowired
    private PaperMapper paperMapper;

    @Autowired
    private PaperQuestionMapper paperQuestionMapper;

    @Autowired
    private QuestionStoreMapper questionStoreMapper;

    /**
     * 查询学院试卷
     *
     * @param id 学院试卷ID
     * @return 学院试卷
     */
    @Override
    public CollegePaper selectCollegePaperById(Long id)
    {
        List<CollegePaperQuestion> paperQuestionList = collegePaperQuestionMapper.selectCollegePaperQuestionList(new CollegePaperQuestion(){{
            setCollegePaperId(id);
        }});

        List<Map<String,Object>> resp = new ArrayList<>();
        CollegePaper collegePaper = collegePaperMapper.selectCollegePaperById(id);
        for (CollegePaperQuestion paperQuestion : paperQuestionList){
            Map<String,Object> map = new HashMap<>();
            map.put("id",paperQuestion.getId());
            map.put("collegePaperId",paperQuestion.getCollegePaperId());
            map.put("questionStoreId",paperQuestion.getQuestionStoreId());
            map.put("score",paperQuestion.getScore());
            resp.add(map);
        }
        collegePaper.setList(resp);

        return collegePaper;
    }

    /**
     * 查询学院试卷列表
     *
     * @param collegePaper 学院试卷
     * @return 学院试卷
     */
    @Override
    public List<CollegePaper> selectCollegePaperList(CollegePaper collegePaper)
    {
       if( SpringUtils.getBean(TokenService.class).getLoginUser(ServletUtils.getRequest()).getUser().getUserId()!=1){
           collegePaper.setCollegeId(SpringUtils.getBean(TokenService.class).getLoginUser(ServletUtils.getRequest()).getCollegeStaff().getCollegeId());
       }
        return collegePaperMapper.selectCollegePaperList(collegePaper);
    }

    /**
     * 新增学院试卷
     *
     * @param collegePaper 学院试卷
     * @return 结果
     */
    @Override
    @Transactional
    public int insertCollegePaper(CollegePaper collegePaper, LoginUser loginUser)
    {
        CollegeStaff collegeStaff = loginUser.getCollegeStaff();
        collegePaper.setCollegeId(collegeStaff.getCollegeId());
        collegePaper.setCollegeName(collegeStaff.getCollegeName());
        collegePaper.setSyncDt(new Date());
        if(collegePaper.getPaperId()!=null){
            Paper paper = paperMapper.selectPaperById(collegePaper.getPaperId());
            collegePaper.setName(paper.getName());
        }
        int i = 0;
        if(collegePaper.getPaperId()==null){
            //判断题目数量
            if( collegePaper.getList().size() > 0 ){
                collegePaper.setQuestionCount( Long.parseLong(collegePaper.getList().size()+""));
            }else{
                throw new CustomException("请至少选择一个题目作为试卷内容");
            }
            //判断小项分数之和是否等于总分
            Double sum = collegePaper.getList().stream().collect(Collectors.summingDouble(c -> Double.valueOf(c.get("score")+"")));
            collegePaper.setScore(sum);
            //判断总分是否大于合格分
            /**
             * int a = bigdemical.compareTo(bigdemical2)
             *
             * a = -1,表示bigdemical小于bigdemical2；
             *
             * a = 0,表示bigdemical等于bigdemical2；
             *
             * a = 1,表示bigdemical大于bigdemical2；
             */

            if(collegePaper.getScore().compareTo(collegePaper.getStandardScore())!=1){
                throw new CustomException("总分需大于合格分");
            }
            if(collegePaper.getScore().compareTo(sum)!=0){
                throw new CustomException("总分需等于各题目分数之和");
            }
              i = collegePaperMapper.insertCollegePaper(collegePaper);
        }else{
            //系统组卷
            //先查询系统卷详情
            Paper paper = paperMapper.selectPaperById(collegePaper.getPaperId());
            collegePaper.setName(paper.getName());
            collegePaper.setScore(paper.getScore());
            collegePaper.setStandardScore(paper.getStandardScore());
            collegePaper.setQuestionCount(paper.getQuestionCount());
              i = collegePaperMapper.insertCollegePaper(collegePaper);

            PaperQuestion paperQuestion = new PaperQuestion();
            paperQuestion.setPaperId(paper.getId());
            List<PaperQuestion> paperQuestions = paperQuestionMapper.selectPaperQuestionList(paperQuestion);
            if(paperQuestions != null && paperQuestions.size() != 0)
            for (PaperQuestion map : paperQuestions) {
                CollegePaperQuestion collegePaperQuestion = new CollegePaperQuestion();
                collegePaperQuestion.setCollegePaperId(collegePaper.getId());
                collegePaperQuestion.setQuestionStoreId(map.getQuestionStoreId());
                collegePaperQuestion.setScore(map.getScore());
                collegePaperQuestionMapper.insertCollegePaperQuestion(collegePaperQuestion);
            }
                collegePaperMapper.updatePaperId();
        }
        //学校组卷
        List<Map<String, Object>> list = collegePaper.getList();
        if(list != null && list.size() != 0)
        for (Map<String, Object> map : list) {

            CollegePaperQuestion collegePaperQuestion = new CollegePaperQuestion();
            collegePaperQuestion.setCollegePaperId(collegePaper.getId());
            collegePaperQuestion.setQuestionStoreId(Long.parseLong(map.get("questionStoreId")+""));
            collegePaperQuestion.setScore(Double.valueOf(map.get("score")+""));
            collegePaperQuestionMapper.insertCollegePaperQuestion(collegePaperQuestion);
        }
        return i;


    }

    /**
     * 修改学院试卷
     *
     * @param collegePaper 学院试卷
     * @return 结果
     */
    @Override
    @Transactional
    public int updateCollegePaper(CollegePaper collegePaper)
    {
        //先删除学院考试题库表
        collegePaperQuestionMapper.deleteCollegePaperQuestionByCollegeId(collegePaper.getId());

        if(collegePaper.getPaperId()==0){
           //学院组卷
            //判断题目数量
            if( collegePaper.getList().size() > 0 ){
                collegePaper.setQuestionCount( Long.parseLong(collegePaper.getList().size()+""));
            }else{
                throw new CustomException("请至少选择一个题目作为试卷内容");
            }
            Double sum = collegePaper.getList().stream().collect(Collectors.summingDouble(c -> Double.valueOf(c.get("score")+"")));
            collegePaper.setScore(sum);

            //判断总分是否大于合格分
            if(collegePaper.getScore().compareTo(collegePaper.getStandardScore())!=1){
                throw new CustomException("总分需大于合格分");
            }

            //判断小项分数之和是否等于总分
            if(collegePaper.getScore().compareTo(sum)!=0){
                throw new CustomException("总分需等于各题目分数之和");
            }
        }else{
            //系统组卷
            Paper paper = paperMapper.selectPaperById(collegePaper.getPaperId());

            collegePaper.setName(paper.getName());
            collegePaper.setScore(paper.getScore());
            collegePaper.setStandardScore(paper.getStandardScore());
            collegePaper.setQuestionCount(paper.getQuestionCount());

            PaperQuestion paperQuestion = new PaperQuestion();
            paperQuestion.setPaperId(paper.getId());
            List<PaperQuestion> paperQuestions = paperQuestionMapper.selectPaperQuestionList(paperQuestion);
            if(paperQuestions != null && paperQuestions.size() != 0)
                for (PaperQuestion map : paperQuestions) {
                    CollegePaperQuestion collegePaperQuestion = new CollegePaperQuestion();
                    collegePaperQuestion.setCollegePaperId(collegePaper.getId());
                    collegePaperQuestion.setQuestionStoreId(map.getQuestionStoreId());
                    collegePaperQuestion.setScore(map.getScore());
                    collegePaperQuestionMapper.insertCollegePaperQuestion(collegePaperQuestion);
                }

        }

        List<Map<String, Object>> list = collegePaper.getList();
        if(list != null && list.size() != 0)
            for (Map<String, Object> map : list) {
            CollegePaperQuestion collegePaperQuestion = new CollegePaperQuestion();
            collegePaperQuestion.setCollegePaperId(collegePaper.getId());
            collegePaperQuestion.setQuestionStoreId(Long.parseLong(map.get("questionStoreId")+""));
            collegePaperQuestion.setScore(Double.valueOf(map.get("score")+""));
            collegePaperQuestionMapper.insertCollegePaperQuestion(collegePaperQuestion);
        }
        return collegePaperMapper.updateCollegePaper(collegePaper);
    }

    /**
     * 批量删除学院试卷
     *
     * @param ids 需要删除的学院试卷ID
     * @return 结果
     */
    @Override
    @Transactional
    public int deleteCollegePaperByIds(Long[] ids)
    {
        for(Long id : ids){
            collegePaperQuestionMapper.deleteCollegePaperQuestionByCollegeId(id);
        }

        return collegePaperMapper.deleteCollegePaperByIds(ids);
    }

    /**
     * 删除学院试卷信息
     *
     * @param id 学院试卷ID
     * @return 结果
     */
    @Override
    public int deleteCollegePaperById(Long id)
    {
        collegePaperQuestionMapper.deleteCollegePaperQuestionByCollegeId(id);
        return collegePaperMapper.deleteCollegePaperById(id);
    }

    /**
     * 获取超管中的试卷信息
     */

    @Override
    public Paper getParerQueList(Long id) {

        List<PaperQuestion> paperQuestionList = paperQuestionMapper.selectPaperQuestionList(new PaperQuestion(){{
            setPaperId(id);
        }});
        List<Map<String,Object>> resp = new ArrayList<>();
        Paper paper = paperMapper.selectPaperById(id);
        for (PaperQuestion paperQuestion : paperQuestionList){
            Map<String,Object> map = new HashMap<>();
            QuestionStore questionStore = questionStoreMapper.selectQuestionStoreById(paperQuestion.getQuestionStoreId().intValue());
           if(questionStore != null){
               map.put("typeName",questionStore.getTypeName() == null ? "" : questionStore.getTypeName());
               map.put("content",questionStore.getContent()  == null ? "" : questionStore.getContent());
               map.put("score",paperQuestion.getScore()  == null ? "" : paperQuestion.getScore());
               resp.add(map);
           }
        }
        paper.setList(resp);
        return paper;
    }
}
